<?php

namespace common\models\spread;

use Yii;
use common\models\member\Member;

/**
 * This is the model class for table "{{%spread_attract}}".
 *
 * @property int $id
 * @property int $user_id
 * @property int $token_id
 * @property int $connect_id
 * @property int $branch_user_id
 * @property string $mobile 手机号
 * @property int $status 状态
 * @property int $created_at 绑定时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at
 */
class SpreadAttract extends \common\db\ActiveRecord {

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%spread_attract}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'connect_id', 'branch_user_id', 'token_id', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['mobile'], 'string', 'max' => 11],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'token_id' => 'token ID',
            'connect_id' => 'connect ID',
            'branch_user_id' => 'branch user ID',
            'mobile' => '手机号',
            'status' => '状态',
            'created_at' => '绑定时间',
            'updated_at' => '更新时间',
            'deleted_at' => 'Deleted At',
        ];
    }

    public function getMember() {
        return $this->hasOne(Member::class, ['user_id' => 'user_id'])->active(Member::STATUS_ACTIVE)->andWhere([
            'audit_status' => Member::AUDIT_STATUS_FINISH
        ]);
    }

    public function getConnect() {
        return $this->hasOne(\common\models\user\UserConnect::class, ['id' => 'connect_id']);
    }

    public function getToken() {
        return $this->hasOne(\common\models\app\AppToken::class, ['id' => 'token_id']);
    }

    public static function findByMobile($mobile) {
        return static::findOne(['mobile' => $mobile]);
    }

    public static function registerTokenUser($user_id, $token) {
        if (!$token) {
            return null;
        }
        $model = static::find()->active()->andWhere([
            'token_id' => $token->id,
        ])->one();
        if (!$model) {
            $model = new SpreadAttract();
            $model->attributes = [
                'user_id' => $user_id,
                'token_id' => $token->id,
                'status' => static::STATUS_DEFAULT,
            ];
            if (!$model->save()) {
                return $model->saveError();
            }
        }
        return $model;
    }

}
